import shutil
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from menuinst.win32 import folder_path
from config import *


def rename(directory, new_prefix):
    count = 1
    for filename in os.listdir(directory):
        if filename.endswith('.txt'): # 暂只处理txt文件
            old_file = os.path.join(directory, filename) # 将目录路径和文件名拼接成完整的旧文件路径
            new_file = os.path.join(directory, f'{new_prefix}_{count}.txt')
            shutil.move(old_file, new_file)
            print(f"begin to rename the {count} file")
            count += 1
    print("End!")


def send_email(sender_email, sender_password, receiver_email, subject, email_file_path):
    # 创建一个多部分消息
    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = receiver_email
    # 邮件主题
    message["Subject"] = subject

    # 读取目录文件夹下所有txt文件内容
    email_body = ""
    if os.path.exists(email_file_path):
        for filename in os.listdir(email_file_path):
            if filename.endswith('.txt'):
                file_path = os.path.join(email_file_path, filename)
                try:
                    with open(file_path, 'r', encoding='utf-8') as file:
                        content = file.read()
                        email_body += f"文件名：{filename}\n"
                        email_body += content
                        email_body += "\n\n"
                except Exception as e:
                    print(f"读取{filename}时出错：{e}")
            print(f"读取{filename}成功")

    # 添加到邮件正文
    message.attach(MIMEText(email_body, "plain")) # 纯文本格式


    try:
        with smtplib.SMTP_SSL("smtp.163.com", 465) as server:
            # 登录发件人邮箱，这里的 sender_password 应该是网易邮箱的授权码
            server.login(sender_email, sender_password)
            # 发送邮件
            text = message.as_string()
            server.sendmail(sender_email, receiver_email, text)
            print("邮件发送成功")
    except Exception as e:
        print(f"邮件发送失败: {e}")

# rename(Rename_path, New_prefix)
send_email(sender_email, sender_password, receiver_email, subject, Email_file_path)